﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.IO;
using Luna;
using System.Diagnostics;

namespace VulnDBExplorer.Services.Impl {
	class FileComparator: ShellExecutor, IFileComparator {

		Regex CMD_PAT = new Regex("(\\d+)(,(\\d+))?([adc])(\\d+)(,(\\d+))?", RegexOptions.Singleline);

		public FileCompareResult compare(string lfile, string rfile) {
			FileCompareResult result = new FileCompareResult(lfile, rfile);
			
			string arg = string.Format("-i -w \"{0}\" \"{1}\"", lfile, rfile); // -i -w
			StreamReader output = shellExecute("diff.exe", arg);
			while (!output.EndOfStream) {
				string line = output.ReadLine();
				Match m = CMD_PAT.Match(line);
				if (m.Success && m.Index == 0) {
					char cmd = m.Groups[4].Value[0];
					int sline;
					FileCompareResult.FileChunk c = FileCompareResult.FileChunk.Empty;

					if (cmd == 'd' || cmd == 'c')
						result.LeftChange.Add(c = new FileCompareResult.FileChunk() { 
							Begin = sline = m.Groups[1].Value.toInt(),
							End = m.Groups[3].Value.toInt(sline),
							Op = cmd
						});
					if (cmd == 'a' || cmd == 'c')
						result.RightChange.Add(c = new FileCompareResult.FileChunk() {
							Begin = sline = m.Groups[5].Value.toInt(),
							End = m.Groups[7].Value.toInt(sline),
							Op = cmd
						});

					if (c.Begin == 0 || c.End == 0)
						Debugger.Break();
				}
			}

			//result.LeftChange.Sort((a, b) => a.Begin - b.Begin);
			//result.RightChange.Sort((a, b) => a.Begin - b.Begin);
			return result;
		}
	}
}
